package com.atguigu.gmall.weball.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.feignclients.cart.CartFeignClient;
import com.atguigu.gmall.product.entity.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName CartController
 * @Description TODO
 * @Author king
 * @Date 2022/11/16 11:56
 * @Version 1.0
 */

@Controller
public class CartController {

    @Autowired
    CartFeignClient cartFeignClient;

    ///cart/deleteChecked
    @GetMapping("/cart/deleteChecked")
    public String deleteChecked(){

        cartFeignClient.deleteChecked();

        return "redirect:http://cart.gmall.com/cart.html";

    }

    @GetMapping("/cart.html")
    public String cartPage(){
        return "cart/index";
    }

    //任何容器长期一直在内存, 就一定要考虑内部的元素用完就删.......
   //public static Map<Thread, HttpServletRequest> threadInfo = new ConcurrentHashMap<>();

   //同一个线程共享数据[呵呵]
   public static ThreadLocal<HttpServletRequest> threadLocal = new ThreadLocal<>();

    //addCart.html?skuId=58&skuNum=1&sourceType=query
    @GetMapping("/addCart.html")
    public String addToCart(@RequestParam("skuId") Long skuId,
                            @RequestParam("skuNum") Integer skuNum,
                            HttpServletRequest request,
                            Model model){



        //threadInfo.put(Thread.currentThread(),request);
        //threadLocal.set(request); //把指定数据共享到指定线程中


        //情头传递下去
        //String tempid = request.getHeader("userTempId");
        //===远程调用购物车服务=====商品入库
        Result<SkuInfo> result = cartFeignClient.addToCart(skuId, skuNum);

        if(result.isOk()) {
            threadLocal.remove();  //用完就删
            model.addAttribute("skuInfo",result.getData());
            model.addAttribute("skuNum", skuNum);

            return "cart/addCart";
        } else {
            model.addAttribute("msg", result.getMessage());
            return "cart/addCartError";
        }



    }

}
